package com.zhp.filter;

import com.zhp.service.UserService;
import com.zhp.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 判断是否己住登录，如果是，则自动跳转主页面
 */
@WebFilter("/index.jsp")
public class SignFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        Cookie[] cookies = req.getCookies();
        UserService userService = new UserServiceImpl();
        for (Cookie c :cookies) {
            if ("username".equals(c.getName())){
                Map<String,Object> userinfomap = userService.findUserBaseInfo(c.getName());
                req.getSession().setAttribute("userinfomap",userinfomap);
                req.getSession().setAttribute(req.getSession().getId(), userinfomap.get("userId").toString());
                resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
